<template>
    <van-uploader
        v-model="filelist"
        :before-read="asyncBeforeRead"
        :after-read="afterRead"
        :before-delete="beforeDelete"
    >
    </van-uploader>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { reqPicture } from '@/api/student';
const emit = defineEmits(['upload']);

const filelist = ref([]);
let fileIdList = [];

const compress = (fileObj, callback) => {
    try {
        const image = new Image();
        image.src = URL.createObjectURL(fileObj);
        image.onload = function () {
            const that = this;
            // 默认按比例压缩
            let w = that.width;
            let h = that.height;
            const scale = w / h;
            w = fileObj.width || w;
            h = fileObj.height || w / scale;
            let quality = 0.7; // 默认图片质量为0.7
            // 生成canvas
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            // 创建属性节点
            const anw = document.createAttribute('width');
            anw.nodeValue = w;
            const anh = document.createAttribute('height');
            anh.nodeValue = h;
            canvas.setAttributeNode(anw);
            canvas.setAttributeNode(anh);
            ctx.drawImage(that, 0, 0, w, h);
            // 图像质量
            if (
                fileObj.quality &&
                fileObj.quality <= 1 &&
                fileObj.quality > 0
            ) {
                quality = fileObj.quality;
            }
            // quality值越小，所绘制出的图像越模糊
            const data = canvas.toDataURL('image/jpeg', quality);
            // 压缩完成执行回调
            const newFile = convertBase64UrlToBlob(data);
            callback(newFile);
        };
    } catch (e) {}
};

const ListChange = () => {
    emit('upload', { data: fileIdList });
};

const beforeDelete = (file, detail) => {
    fileIdList.splice(detail.index, 1);
    ListChange();
    ElMessage({
        type: 'success',
        message: '删除成功！'
    });
    return true;
};

const asyncBeforeRead = file => {
    return new Promise((resolve, reject) => {
        if (
            file.type == 'image/jpg' ||
            file.type == 'image/png' ||
            file.type == 'image/jpeg' ||
            file.type == 'image/png' ||
            file.type == 'image/bmp'
        ) {
            if (file.size / 1024 < 10240) {
                //上传图片是否重复
                let blob = false;
                filelist.value.forEach(element => {
                    if (file.name === element.file.name) {
                        blob = true;
                        return;
                    }
                });
                if (blob) {
                    ElMessage({
                        type: 'error',
                        message: '文件已存在'
                    });
                    reject();
                    return;
                }
                if (file.size / 1024 > 5121) {
                    compress(file, res => {
                        ElMessage({
                            type: 'success',
                            message: '上传成功！'
                        });
                        resolve(res);
                    });
                }
                ElMessage({
                    type: 'success',
                    message: '上传成功！'
                });
                resolve(file);
            } else {
                ElMessage({
                    type: 'error',
                    message: '上传图片大小不得大于10M！'
                });
                reject();
            }
        } else {
            ElMessage({
                type: 'error',
                message: '请上传标准格式的图片(.jpg、.png、.jpeg、.png、.bmp)'
            });
            reject();
        }
    });
};

const afterRead = async (file, detail) => {
    try {
        const result = await reqPicture(file.file);
        fileIdList.push(result.data);
        ListChange();
    } catch (error) {
        throw new Error(error);
    }
};
</script>

<style lang="scss" scoped></style>
